﻿
#region NameSpace
using System;
using System.Configuration;
using System.Data;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using Purchase;
using System.ComponentModel;
using System.Drawing;
using System.Web.SessionState;
using System.IO;
using System.Text;
using System.Net;
using iTextSharp.text;
using iTextSharp.text.pdf;
using iTextSharp.text.html;
using iTextSharp.text.html.simpleparser;
using EB.BPARequestManagement;
using Eb.MessageBox;
using System.Collections;
using System.Collections.Specialized;
using EB.Inbox;
#endregion

public partial class Modules_Purchase_ucPurchaseOrder : System.Web.UI.UserControl
{
    #region Fields
    EB.Inbox.Inbox inBoxCreate = new EB.Inbox.Inbox();
    RequestCreate requestCreate = new RequestCreate();
    Purchase.Purchase purchase = new Purchase.Purchase();
    static double grdTotal = 0;
    static double grdTotalGeneral1 = 0;
    static int linkKey = 0;
    private double runningTotal = 0;
    int requestType = 0;
    static double expectedAmount = 0;
    static int grdSelectUniqId = 0;
    static int statusId = 0;
    static int grdselectGeneralUniqId = 0;
    static int requesterId = 0;
    static int requestListUniqRecordNumber = 0;
    #endregion

    #region Events
    protected void Page_Load(object sender, EventArgs e)
    {
        Stylesheet.Attributes.Add("href", "../../Css/SkylineFair.css");
        Stylesheet.Attributes.Add("type", "text/css");
        Stylesheet.Attributes.Add("rel", "stylesheet");
        TabContainer1.CssClass = "";
        if (Request.QueryString["Sel"] != null)
        {
            char splitter = ';';
            string path = Request.Params["Sel"].ToString();
            string[] splitid = path.Split(splitter);

            string URL = splitid[0];
            string FileName = URL.Substring(URL.LastIndexOf("/") + 1, (URL.Length - URL.LastIndexOf("/") - 1));
            if (FileName == "ucPurchaseOrder.ascx")
            {
                Session["hasrequestLinkId"] = null;
                Session["requestTypeId"] = null;
                TabContainer1.CssClass = "blue";

            }
        }
        btnPrint.Attributes.Add("Onclick", "getPrint('Print_All');");
        // btnPrint.Attributes.Add("onclick", "javascript:printPreviewDiv('DivForPrint1')");

        if (!IsPostBack)
        {
            GetProductionWisePurchasedItems();
            GetProducts();
            GetGeneralPurchasedItems();



        }
        if (TabContainer1.ActiveTabIndex == 0)
        {
            requestType = 1;

        }
        else
        {
            requestType = 2;
            //btnProductionSave.Visible = false;
            //Button1.Visible = true;

        }
        //  GetMaterials();
        txtActualLeadTime.Text = DateTime.Now.ToShortDateString();
        txtGeneralActualLeadDate.Text = DateTime.Now.ToShortDateString();
        txtGeneralExpectedLeadDate.Text = DateTime.Now.ToShortDateString();
        txtDueDate.Text = DateTime.Now.ToShortDateString();
        lblD.Text = DateTime.Now.ToShortDateString();
        lblD1.Text = DateTime.Now.ToShortDateString();

        if (Session["hasrequestLinkId"] != null && Session["requestTypeId"] != null)
        {
            btnViewPurchaseOrder.Visible = false;
            pnlGeneralView.Visible = true;
            grvViewItemDetailsGeneral.Visible = true;
            int typeId = purchase.GetPurchaseTypeByOrder(Convert.ToInt16(Session["hasrequestLinkId"]));
            int uniqId = Convert.ToInt16(Session["hasrequestLinkId"]);
            if (typeId == 2)
            {

                TabContainer1.ActiveTabIndex = 1;
                DataSet purchasedItemDS = purchase.GetGeneralPurchaseOrderedDetailsByRequestId(uniqId);
                grvViewItemDetailsGeneral.DataSource = purchasedItemDS;
                grvViewItemDetailsGeneral.DataBind();

            }
            else
            {
                GetProducts();
                TabContainer1.ActiveTabIndex = 0;
                btnViewPurchaseReq.Visible = false;
                 btnCreatePurchaseOrder.Visible = false;
                btnPrint.Visible = false;
                btnExportToPdf.Visible = false;
                DataSet purchaseDS = purchase.GetPurchaseOrderMasterDetails(uniqId);
                if (purchaseDS.Tables[0].Rows.Count > 0)
                {
                    TabContainer1.Tabs[1].HeaderText = string.Empty;
                    TabContainer1.Tabs[0].HeaderText = string.Empty;
                    // TabContainer2.Enabled = false;
                    TabContainer1.Tabs[1].CssClass = "InboxTableHeader";
                    TabContainer1.Tabs[0].CssClass = "InboxTableHeader";
                    TabPanel1.CssClass = "InboxTableHeader";
                    TabPanel2.CssClass = "InboxTableHeader";

                    ddlProductName.Visible = true;
                    txtQty.Visible = true;
                    txtActualLeadTime.Visible = true;
                    txtDueDate.Visible = true;
                    lblD1.Visible = true;
                    pnlView.Visible = true;
                    pnlView1.Visible = true;
                    ddlProductName.SelectedValue = purchaseDS.Tables[0].Rows[0]["PR_ProductID"].ToString();
                    txtQty.Text = purchaseDS.Tables[0].Rows[0]["PR_ProductQuantity"].ToString();
                    txtActualLeadTime.Text = purchaseDS.Tables[0].Rows[0]["PR_ActualLeadTime"].ToString();
                    txtDueDate.Text = purchaseDS.Tables[0].Rows[0]["PR_ExpectedLeadTime"].ToString();
                    lblD1.Text = purchaseDS.Tables[0].Rows[0]["PR_DateTime"].ToString();
                    ddlProductName.Enabled = false;
                    txtQty.Enabled = false;
                    txtActualLeadTime.Enabled = false;
                    txtDueDate.Enabled = false;
                    if (uniqId != 0)
                    {
                        int productId = Convert.ToInt16(ddlProductName.SelectedValue);
                        DataSet materialDS = purchase.GetPuchaseOrderedItemsByRequestId(uniqId);
                        grvMaterialDetails.DataSource = materialDS;
                        grvMaterialDetails.DataBind();
                    }
                }

            }

        }

    }
    protected void btnPrint_Click(object sender, EventArgs e)
    {
        // Session["ctrl"] = Panel1;
        // Page.ClientScript.RegisterStartupScript(this.GetType(), "onclick", "<script language=javascript>window.open('BusinessProcessAutomation.aspx','PrintMe','height=300px,width=300px,scrollbars=1');</script>");
    }
    /// <summary>
    /// Delete Item From GridView
    /// </summary>
    /// <param name="sender"></param>
    /// <param name="e"></param>
    protected void btnDeleteBomList_Click(object sender, EventArgs e)
    {
        string path = string.Empty;
        ImageButton btn = (ImageButton)sender;
        string requestUniqId = btn.CommandArgument;
        int uniqID = Convert.ToInt16(requestUniqId);
        bool status = purchase.DeleteBOMList(uniqID);
        if (status)
        {
            lblProductionWisePurchaseMessage.Visible = true;
            lblProductionWisePurchaseMessage.Text = "Deleted Successfully";
            GetProductionWisePurchasedItems();
        }
        else
        {
            lblProductionWisePurchaseMessage.Visible = true;
            lblProductionWisePurchaseMessage.Text = "Couldnt Delete Item From BOM List";
        }
    }
   
 

    /// <summary>
    /// 
    /// </summary>
    /// <param name="sender"></param>
    /// <param name="e"></param>
    protected void grvViewPurchasedItems_PageIndexChanging(object sender, GridViewPageEventArgs e)
    {
        grvViewPurchasedItems.PageIndex = e.NewPageIndex;
        GetProductionWisePurchasedItems();
    }

    /// <summary>
    /// 
    /// </summary>
    /// <param name="sender"></param>
    /// <param name="e"></param>
    protected void TabContainer1_ActiveTabChanged(object sender, EventArgs e)
    {
        if (TabContainer1.ActiveTabIndex == 0)
        {
            requestType = 1;
        }
        else
        {
            requestType = 2;
            //btnProductionSave.Visible = false;
            //Button1.Visible = true;

        }
    }


   
    protected void btnGeneralNewPurchaseRequest_Click(object sender, EventArgs e)
    {
        GeneralPurchaseRequestClearControls();
    }

    protected void btnGeneralExportToPdf_Click(object sender, EventArgs e)
    {
        if (grdselectGeneralUniqId <=0)
        {
            MessageBox.Show("Please select an Item from the table RepeatOrder");
            // lblProductionWisePurchaseMessage.Visible = true;
            // lblProductionWisePurchaseMessage.Text = "Please select an Item ";

        }
        else if (grdselectGeneralUniqId != 0)
        {
            CreateGeneralPDFDocument();
        }
    }
    protected void btnExportToPdf_Click(object sender, EventArgs e)
    {
        if (grvViewPurchasedItems.SelectedIndex == -1)
        {
            MessageBox.Show("Please select an Item from the table RepeatOrder");
            // lblProductionWisePurchaseMessage.Visible = true;
            // lblProductionWisePurchaseMessage.Text = "Please select an Item ";

        }
        else
        {
            if (grdSelectUniqId != 0 && statusId == 5)
            {
                CreatePDFDocument();

            }
            else
            {
                MessageBox.Show("Waiting to approve");

            }

        }


       
    }




    /// <summary>
    /// Bind Materials By selecting Product
    /// </summary>
    /// <param name="sender"></param>
    /// <param name="e"></param>
    protected void ddlProductName_SelectedIndexChanged1(object sender, EventArgs e)
    {
       
    }

    protected void ddlItmName_SelectedIndexChanged(object sender, EventArgs e)
    {


    }

  
 

    protected void btnViewPurchaseReq_Click(object sender, EventArgs e)
    {
        Session["UserManager_Control"] = "Purchase/SerchPyrchaseRequest.ascx";
        Response.Redirect("BusinessProcessAutomation.aspx?reqType=" + requestType);
        //  Response.Redirect("BusinessProcessAutomation.aspx?linkKey=" + System.Convert.ToInt32(linkKey) + "&RequestType=" + requestTypeId);

    }


  
    /// <summary>
    /// 
    /// </summary>
    /// <param name="sender"></param>
    /// <param name="e"></param>
    /// 

    protected void grvMaterialDetails_RowDataBound(object sender, GridViewRowEventArgs e)
    {

        if (e.Row.RowType == DataControlRowType.DataRow)
        {
            int materialId = 0;
            string lblUnit = ((Label)e.Row.FindControl("lblMaterialId")).Text;
            if (lblUnit != "")
                materialId = Convert.ToInt16(lblUnit);

            DataSet vendorDS = purchase.GetVendorDetails(materialId);
            DropDownList ddl = (DropDownList)e.Row.FindControl("ddlVendorName");
            ddl.DataSource = vendorDS;
            ddl.DataValueField = "VendorID";
            ddl.DataTextField = "VR_VendorName";
            ddl.DataBind();
        }
        if (grdSelectUniqId > 0)
        {
            if (e.Row.RowType == DataControlRowType.DataRow)
            {
                if (statusId == 4)
                {
                    int vendorId = 0;
                    int materialId = 0;
                    string lblUnit = ((Label)e.Row.FindControl("lblMaterialId")).Text;
                    if (lblUnit != "")
                        materialId = Convert.ToInt16(lblUnit);
                    DropDownList ddl = (DropDownList)e.Row.FindControl("ddlVendorName");
                    vendorId = purchase.GetVendorNameByMaterialIDAndRequestId(grdSelectUniqId, materialId);
                    ddl.SelectedValue = vendorId.ToString();
                   // grvMaterialDetails.Columns[3].Visible = true;
                }

            }
        }

        // }
        // }


        if (e.Row.RowType == DataControlRowType.DataRow)
        {

            e.Row.Attributes.Add("onmouseover", "MouseEvents(this, event)");

            e.Row.Attributes.Add("onmouseout", "MouseEvents(this, event)");

        }
        if (e.Row.RowType == DataControlRowType.EmptyDataRow)
            e.Row.CssClass = "grid-view-header";

        if (e.Row.RowType == DataControlRowType.Header)
            e.Row.CssClass = "grid-view-header";

        //Add CSS class on normal row.
        if (e.Row.RowType == DataControlRowType.DataRow &&
                  e.Row.RowState == DataControlRowState.Normal)
            e.Row.CssClass = "grid-view-normal";

        //Add CSS class on alternate row.
        if (e.Row.RowType == DataControlRowType.DataRow &&
                  e.Row.RowState == DataControlRowState.Alternate)
            e.Row.CssClass = "grid-view-alternate";


        double amt = 0;
        //  double totalAmt = 0;
        //if (e.Row.RowType == DataControlRowType.Header)
        //{
        //    totalAmt = 0;
        //}
        int uQty = 0;
        double amount = 0;
        int qty = 0;
        foreach (GridViewRow gvr in grvMaterialDetails.Rows)
        {


            // float price = float.Parse(gvr.Cells[3].Text.Trim()); //get the price
            TextBox price = (TextBox)gvr.Cells[3].FindControl("txtUnitPrice");
            double price1 = Convert.ToDouble(price.Text);
            TextBox tbQty = (TextBox)gvr.Cells[2].FindControl("txtQuantity"); //get the quantity TextBox
            TextBox tbTotal = (TextBox)gvr.Cells[5].FindControl("txtTotal"); //get the total TextBox
            Label lblUnit = (Label)gvr.Cells[1].FindControl("lblUnit");


            int totQty = Convert.ToInt16(txtQty.Text);
            //if (int.TryParse(tbQty.Text.Trim(), out qty))
            //{
            qty = Convert.ToInt16(tbQty.Text);
            if (lblUnit.Text != "")
                uQty = Convert.ToInt16(lblUnit.Text);
            else
                uQty = 0;
            tbQty.Text = Convert.ToString(uQty * totQty);

            qty = Convert.ToInt16(tbQty.Text);
            amount = price1 * qty;
            tbTotal.Text = amount.ToString("C2");
            grdTotal = amount + amt;
            amt = grdTotal;

        }

        if (e.Row.RowType == DataControlRowType.Footer)
        {
            e.Row.Cells[6].Text = "Total Amount:";
            e.Row.Cells[7].Text = grdTotal.ToString("C2");
            expectedAmount = grdTotal;
        }

   
    }

 
    protected void UpdateGeneralPurchaseRequest()
    {
        if (grdselectGeneralUniqId != 0)
        {
            if (grvViewItemDetailsGeneral.Rows.Count > 0)
            {
                foreach (GridViewRow gvr in grvViewItemDetailsGeneral.Rows)
                {
                   // TextBox txtProduct = (TextBox)gvr.Cells[0].FindControl("txtProduct1");
                    TextBox txtProduct = (TextBox)gvr.Cells[0].FindControl("txtProduct1");
                    TextBox txtSpecification = (TextBox)gvr.Cells[0].FindControl("txtSpecification1");
                    TextBox txtUnitPrice = (TextBox)gvr.Cells[2].FindControl("txtUnitPrice1");
                    TextBox txtRequiredQty = (TextBox)gvr.Cells[3].FindControl("txtRequiredQty1");
                   // bool status = purchase.UpdateGeneralPurchaseRequest(grdselectGeneralUniqId, txtProduct.Text, Convert.ToInt16(txtRequiredQty.Text), Convert.ToDouble(txtUnitPrice.Text), txtSpecification.Text);
                }
            }
        }
        else
        {
            MessageBox.Show("Failed to Update");
        }
    }
    /// <summary>
    /// 
    /// </summary>
    /// <param name="sender"></param>
    /// <param name="e"></param>
    protected void txtQuantity_TextChanged(object sender, EventArgs e)
    {

        FindProductionWiseTotalAmount();

    }

   
    protected void txtQty_TextChanged(object sender, EventArgs e)
    {
        if (grvMaterialDetails.Rows.Count > 0)
            FindTotalAmount();
    }


    protected void grvViewPurchasedItems_RowDataBound(object sender, GridViewRowEventArgs e)
    {
        if (e.Row.RowType == DataControlRowType.DataRow)
        {
            statusId = 0;
            string statusNo = ((Label)e.Row.FindControl("lblStatusId")).Text;
            if (statusNo != "")
                statusId = Convert.ToInt16(statusNo);


            e.Row.Attributes.Add("onmouseover", "MouseEvents(this, event)");

            e.Row.Attributes.Add("onmouseout", "MouseEvents(this, event)");

        }
        if (e.Row.RowType == DataControlRowType.EmptyDataRow)
            e.Row.CssClass = "grid-view-header";
        if (e.Row.RowType == DataControlRowType.Header)
            e.Row.CssClass = "grid-view-header";

        //Add CSS class on normal row.
        if (e.Row.RowType == DataControlRowType.DataRow &&
                  e.Row.RowState == DataControlRowState.Normal)
            e.Row.CssClass = "grid-view-normal";

        //Add CSS class on alternate row.
        if (e.Row.RowType == DataControlRowType.DataRow &&
                  e.Row.RowState == DataControlRowState.Alternate)
            e.Row.CssClass = "grid-view-alternate";
    }

   

    #endregion

    #region Methods


    /// <summary>
    /// 
    /// </summary>
    protected void GetProductionWisePurchasedItems()
    {
        int userId=Convert.ToInt16(Session["UserId"].ToString());
        DataSet purchaseDS = purchase.GetPurchaseRequestApprovedInProduction(userId);
        grvViewPurchasedItems.DataSource = purchaseDS;
        grvViewPurchasedItems.DataBind();
    }
    protected void GetGeneralPurchasedItems()
    {
        DataSet purchaseDS = purchase.GetGeneralPurchasedMaterials();
        grvViewGeneralPurchasedItems.DataSource = purchaseDS;
        grvViewGeneralPurchasedItems.DataBind();
    }

    /// <summary>
    /// 
    /// </summary>
    protected void GetProducts()
    {
        DataSet purchaseDS = purchase.GetProducts();
        ddlProductName.DataSource = purchaseDS;
        ddlProductName.DataValueField = "ProductID";
        ddlProductName.DataTextField = "ProductName";
        ddlProductName.DataBind();
        ddlProductName.Items.Insert(0, "-Select-");

      

    }

    /// <summary>
    /// 
    /// </summary>
    /// <param name="_price"></param>
    private void CalcTotal(double _price)
    {
        try
        {
            runningTotal += _price;
        }
        catch (Exception ex)
        {
            HttpContext.Current.Response.Write(ex.ToString());
        }
    }

    /// <summary>
    /// Create First row in Gridview
    /// </summary>


    


   

    
    protected void FindTotalAmount()
    {
        // double netAmount = 0;
        double amt = 0;
        double amount = 0;
        int qty = 0;
        int uQty = 0;
        foreach (GridViewRow gvr in grvMaterialDetails.Rows)
        {
            // float price = float.Parse(gvr.Cells[3].Text.Trim()); //get the price
            TextBox price = (TextBox)gvr.Cells[3].FindControl("txtUnitPrice");
            double price1 = Convert.ToDouble(price.Text);
            TextBox tbQty = (TextBox)gvr.Cells[2].FindControl("txtQuantity"); //get the quantity TextBox
            TextBox tbTotal = (TextBox)gvr.Cells[5].FindControl("txtTotal"); //get the total TextBox
            Label lblUnit = (Label)gvr.Cells[1].FindControl("lblUnit");

            int totQty = Convert.ToInt16(txtQty.Text);
            //if (int.TryParse(tbQty.Text.Trim(), out qty))
            //{
            qty = Convert.ToInt16(tbQty.Text);
            if (lblUnit.Text != "")
                uQty = Convert.ToInt16(lblUnit.Text);
            else
                uQty = 0;
            tbQty.Text = Convert.ToString(uQty * totQty);

            //if (int.TryParse(tbQty.Text.Trim(), out qty))
            //{
            qty = Convert.ToInt16(tbQty.Text);
            amount = price1 * qty;
            //}
            tbTotal.Text = amount.ToString("C2");
            grdTotal = amount + amt;
            amt = grdTotal;

        }
        if (grdTotal != 0)
        {
            ((TextBox)grvMaterialDetails.FooterRow.FindControl("txtGrantTotal")).Visible = true;
            ((TextBox)grvMaterialDetails.FooterRow.FindControl("txtGrantTotal")).Text = grdTotal.ToString("C2");
        }

        //  ((TextBox)grvMaterialDetails.FooterRow.Cells[5].FindControl("txtGrantTotal")).Text = "88";
        expectedAmount = grdTotal;
        //myDataSet.Tables[0].Compute("sum(unitsinstock)", "").ToString();
    }

    protected void FindProductionWiseTotalAmount()
    {
        // double netAmount = 0;
        double amt = 0;
        double amount = 0;
        int qty = 0;
        foreach (GridViewRow gvr in grvMaterialDetails.Rows)
        {
            // float price = float.Parse(gvr.Cells[3].Text.Trim()); //get the price
            TextBox price = (TextBox)gvr.Cells[3].FindControl("txtUnitPrice");
            double price1 = Convert.ToDouble(price.Text);
            TextBox tbQty = (TextBox)gvr.Cells[2].FindControl("txtQuantity"); //get the quantity TextBox
            TextBox tbTotal = (TextBox)gvr.Cells[5].FindControl("txtTotal"); //get the total TextBox
            //Label lblUnit = (Label)gvr.Cells[1].FindControl("lblUnit");

            //if (int.TryParse(tbQty.Text.Trim(), out qty))
            //{

            qty = Convert.ToInt16(tbQty.Text);
            amount = price1 * qty;
            //}
            tbTotal.Text = amount.ToString("C2");
            grdTotalGeneral1 = amount + amt;
            amt = grdTotalGeneral1;


        }
        ((TextBox)grvMaterialDetails.FooterRow.FindControl("txtGrantTotal")).Text = grdTotalGeneral1.ToString("C2");


    }
    public void CreateGeneralPDFDocument()
    {
        MemoryStream MStream = new MemoryStream();
        Document document = new Document(PageSize.A4, 80, 50, 30, 65);
        PdfWriter writer = PdfWriter.GetInstance(document, MStream);

        Phrase footPhraseImg = new Phrase("Page: ", FontFactory.GetFont(FontFactory.TIMES_ROMAN, 8, iTextSharp.text.Font.NORMAL));
        HeaderFooter footer = new HeaderFooter(footPhraseImg, true);
        footer.Border = iTextSharp.text.Rectangle.TOP_BORDER;
        footer.Alignment = Element.ALIGN_RIGHT;
        document.Footer = footer;

        document.Open();

        iTextSharp.text.Image imghead = iTextSharp.text.Image.GetInstance(Server.MapPath("~\\images\\ebirdlogo.jpg"));
        imghead.SetAbsolutePosition(0, 0);
        imghead.Alignment = Element.ALIGN_RIGHT;
        PdfContentByte cbhead = writer.DirectContent;
        PdfTemplate tp = cbhead.CreateTemplate(350, 393);
        tp.AddImage(imghead);
        cbhead.AddTemplate(tp, 30, 740);
        Phrase headPhraseImg = new Phrase(imghead + "", FontFactory.GetFont(FontFactory.TIMES_ROMAN, 7, iTextSharp.text.Font.NORMAL));
        HeaderFooter header = new HeaderFooter(headPhraseImg, true);
        header.Alignment = Element.ALIGN_TOP;
        header.Border = iTextSharp.text.Rectangle.TOP_BORDER;
        Chunk c = new Chunk
             ("\n\n\n\n\n\n Purchase Order Details  \n \n",
             FontFactory.GetFont("Verdana", 15));
        Paragraph p = new Paragraph();
        p.Alignment = Element.ALIGN_CENTER;
        p.Add(c);

        Chunk c1 = new Chunk
      ("Date : \t\t" + lblD.Text + ", \n",
      FontFactory.GetFont("Verdana", 10));
        Paragraph p1 = new Paragraph();
        p1.Alignment = Element.ALIGN_RIGHT;
        p1.Add(c1);

        DataSet purchasedItemDS = purchase.GetGeneralPurchasedDetailsByRequestId(grdselectGeneralUniqId);
        DataTable dt = purchasedItemDS.Tables[0];
        int cols = dt.Columns.Count;
        int rows = dt.Rows.Count;
        iTextSharp.text.Table table = new iTextSharp.text.Table(cols, rows);

        for (int i = 0; i < cols; i++)
        {
            Cell cellCols = new Cell();
            Chunk chunkCols = new Chunk(dt.Columns[i].ColumnName);
            cellCols.Add(chunkCols);
            table.AddCell(cellCols);

        }

        for (int k = 0; k < rows; k++)
        {
            for (int j = 0; j < cols; j++)
            {
                Cell cellRows = new Cell();

                Chunk chunkRows = new Chunk(dt.Rows[k][j].ToString());
                cellRows.Add(chunkRows);
                table.AddCell(cellRows);

            }
        }
        document.Add(p);
        document.Add(p1);
        document.Add(table);
        document.Close();
        HttpContext.Current.Response.Buffer = true;
        // HttpContext.Current.Response.ClearContent();
        // HttpContext.Current.Response.ClearHeaders();
        HttpContext.Current.Response.ContentType = "application/pdf";
        HttpContext.Current.Response.AddHeader("Content-Disposition", "attachment;filename=PurchaseOrderGeneral.pdf");
        HttpContext.Current.Response.BinaryWrite(MStream.GetBuffer());
        HttpContext.Current.Response.End();
        grdselectGeneralUniqId = 0;
    }
    /// <summary>
    /// Creates the PDF document with a given content at a given location.
    /// </summary>
    /// <param name=”strFilePath”>The file path to write the new PDF to.</param>
    /// <param name=”strContent”>Content in HTML to write to the PDF.</param>
 
    public void CreatePDFDocument()
    {
        int vendorId;
        string vendorName = string.Empty;
        string vendorAddress = string.Empty;
        string vendorPhone = string.Empty;
        MemoryStream MStream = new MemoryStream();
        Document document = new Document(PageSize.A4, 80, 50, 30, 65);
        PdfWriter writer = PdfWriter.GetInstance(document, MStream);


        Phrase footPhraseImg = new Phrase("Page: ", FontFactory.GetFont(FontFactory.TIMES_ROMAN, 8, iTextSharp.text.Font.NORMAL));
        HeaderFooter footer = new HeaderFooter(footPhraseImg, true);
        footer.Border = iTextSharp.text.Rectangle.TOP_BORDER;
        footer.Alignment = Element.ALIGN_RIGHT;
        document.Footer = footer;

        document.Open();

        iTextSharp.text.Image imghead = iTextSharp.text.Image.GetInstance(Server.MapPath("~\\images\\ebirdlogo.jpg"));
        imghead.SetAbsolutePosition(0, 0);
        imghead.Alignment = Element.ALIGN_RIGHT;
        PdfContentByte cbhead = writer.DirectContent;
        PdfTemplate tp = cbhead.CreateTemplate(350, 393);
        tp.AddImage(imghead);
        cbhead.AddTemplate(tp, 30, 740);
        Phrase headPhraseImg = new Phrase(imghead + "", FontFactory.GetFont(FontFactory.TIMES_ROMAN, 7, iTextSharp.text.Font.NORMAL));
        HeaderFooter header = new HeaderFooter(headPhraseImg, true);
        header.Alignment = Element.ALIGN_TOP;
        header.Border = iTextSharp.text.Rectangle.TOP_BORDER;

        int requestId = grdSelectUniqId;
        DataSet vendorDS = purchase.GetVendorByRequestId(requestId);
        for (int vendorCount = 0; vendorCount < vendorDS.Tables[0].Rows.Count; vendorCount++)
        {

            string vendor = vendorDS.Tables[0].Rows[vendorCount]["PreferedVendor"].ToString();
            if (vendor != "" || vendor != null)
            {

                vendorId = Convert.ToInt16(vendor);
            }
            else
            {
                vendorId = 0;
            }

            if (vendorId != 0)
            {
                DataSet vendorDetailsDS = purchase.GetVendorDetailsById(vendorId);
                if (vendorDetailsDS.Tables[0].Rows.Count > 0 && vendorId != 0)
                {
                    vendorName = vendorDetailsDS.Tables[0].Rows[0]["VR_VendorName"].ToString();
                    vendorAddress = vendorDetailsDS.Tables[0].Rows[0]["VR_VendorAddress"].ToString();
                    vendorPhone = vendorDetailsDS.Tables[0].Rows[0]["VR_VendorPhone"].ToString();

                }

            }
            else
            {
                vendorName = "Not selected VendorName";
                vendorAddress = string.Empty;
                vendorPhone = "Nil";
            }

            Chunk c = new Chunk
               ("\n\n\n\n\n\n Purchase Request Details  \n \n",
               FontFactory.GetFont("Verdana", 15));
            Paragraph p = new Paragraph();
            p.Alignment = Element.ALIGN_CENTER;
            p.Add(c);

            Chunk chunk11 = new Chunk
           (vendorName + ", \n",
           FontFactory.GetFont("Verdana", 10));
            Paragraph p11 = new Paragraph();
            p11.Alignment = Element.ALIGN_RIGHT;
            p11.Add(chunk11);


            Chunk chunk111 = new Chunk
        (vendorAddress + ", \n",
        FontFactory.GetFont("Verdana", 10));
            Paragraph p111 = new Paragraph();
            p111.Alignment = Element.ALIGN_RIGHT;
            p111.Add(chunk111);

            Chunk chunk1111 = new Chunk
        ("Phone : \t\t" + vendorPhone + ", \n",
        FontFactory.GetFont("Verdana", 10));
            Paragraph p1111 = new Paragraph();
            p1111.Alignment = Element.ALIGN_RIGHT;
            p1111.Add(chunk1111);

            Chunk chunk1 = new Chunk
        ("Product Name  : \t \t",
        FontFactory.GetFont("Verdana", 10));
            Paragraph p1 = new Paragraph();
            p1.Alignment = Element.ALIGN_LEFT;
            p1.Add(chunk1);

            Chunk chunk2 = new Chunk
       (ddlProductName.SelectedItem.ToString() + "\n",
        FontFactory.GetFont("Verdana", 10));
            p1.Add(chunk2);

            Chunk chunk3 = new Chunk
        ("Quantity  \t \t  \t \t  : \t \t",
        FontFactory.GetFont("Verdana", 10));
            Paragraph p2 = new Paragraph();
            p2.Alignment = Element.ALIGN_LEFT;
            p2.Add(chunk3);

            Chunk chunk4 = new Chunk
       (txtQty.Text + "\n",
        FontFactory.GetFont("Verdana", 10));
            p2.Add(chunk4);

            //iTextSharp.text.Table table = new iTextSharp.text.Table(grvMaterialDetails.Columns.Count);
            int productID = Convert.ToInt16(ddlProductName.SelectedValue);
            DataTable dt = purchase.GetVendorDetailsByProductId(productID, vendorId, grdSelectUniqId);
            int cols = dt.Columns.Count;
            int rows = dt.Rows.Count;
            iTextSharp.text.Table table = new iTextSharp.text.Table(cols, rows);

            for (int i = 0; i < cols; i++)
            {
                Cell cellCols = new Cell();
                Chunk chunkCols = new Chunk(dt.Columns[i].ColumnName);
                cellCols.Add(chunkCols);
                table.AddCell(cellCols);

            }

            for (int k = 0; k < rows; k++)
            {
                for (int j = 0; j < cols; j++)
                {
                    Cell cellRows = new Cell();

                    Chunk chunkRows = new Chunk(dt.Rows[k][j].ToString());
                    cellRows.Add(chunkRows);
                    table.AddCell(cellRows);

                }
            }
            //for (int k = 0; k < dt.Columns.Count; k++)
            //{
            //    iTextSharp.text.Cell cell = new iTextSharp.text.Cell(dt.Columns[k].ColumnName.Replace(",", ";") + ',');

            //    // cell.BackgroundColor = new Color(System.Drawing.ColorTranslator.FromHtml("#008000"));
            //    table.AddCell(cell);
            //}

            //for (int i = 0; i < dt.Rows.Count; i++)
            //{

            //    for (int k = 0; k < dt.Columns.Count; k++)
            //    {

            //        //add separator

            //       iTextSharp.text.Cell cell = new iTextSharp.text.Cell(dt.Rows[i][k].ToString().Replace(",", ";") + ',');
            //       table.AddCell(cell);
            //    }

            //    //append new line


            //} 
            document.Add(p);
            document.Add(p11);
            document.Add(p111);
            document.Add(p1111);
            document.Add(p1);
            document.Add(p2);
            document.Add(table);
        }
        document.Close();
        HttpContext.Current.Response.Buffer = true;
        // HttpContext.Current.Response.ClearContent();
        // HttpContext.Current.Response.ClearHeaders();
        HttpContext.Current.Response.ContentType = "application/pdf";
        HttpContext.Current.Response.AddHeader("Content-Disposition", "attachment;filename=PurchaseRequest.pdf");
        HttpContext.Current.Response.BinaryWrite(MStream.GetBuffer());
        HttpContext.Current.Response.End();
    }
    
    private static void PrepareControlForExport(Control control)
    {
        for (int i = 0; i < control.Controls.Count; i++)
        {
            Control current = control.Controls[i];
            if (current is TextBox)
            {
                control.Controls.Remove(current);
                control.Controls.AddAt(i, new LiteralControl((current as TextBox).Text));
            }
        }
    }

    protected void ClearControls()
    {
        ddlProductName.SelectedIndex = 0;
        txtQty.Text = "1";
        txtDueDate.Text = DateTime.Now.ToShortDateString();
        txtActualLeadTime.Text = DateTime.Now.ToShortDateString();
        txtRemarks.Text = string.Empty;
        grvMaterialDetails.DataSource = null;
        grvMaterialDetails.DataBind();
    }

    public void SendRequest()
    {
        //hideeeeee
       // requestCreate.CreateRequest("PurchaseRequest", 0, linkKey);
        int requestTypeId = requestCreate.FindRequestTypeId("PurchaseRequest");
        bool status = purchase.UpdateReQuestStatus(linkKey, requestTypeId, 10);
        int inBoxUniqId = inBoxCreate.CreateInBox(requestTypeId, 10, linkKey);
        bool status1 = inBoxCreate.UpdateInBoxStatus(inBoxUniqId, 10, 1, txtRemarks.Text);
        if (status)
        {
            MessageBox.Show("Forwarded Purchase Request Successfully");
        }
        else
        {
            MessageBox.Show("Failed to Forward.Please try again..");
        }
        GetProductionWisePurchasedItems();
    }

    protected void GeneralPurchaseRequestClearControls()
    {
        txtGeneralPurchaseRemarks.Text = string.Empty;
        txtGeneralActualLeadDate.Text = DateTime.Now.ToShortDateString();
        txtGeneralExpectedLeadDate.Text = DateTime.Now.ToShortDateString();
        lblErrMessage.Text = string.Empty;
        lblErrMessage.Visible = false;
        grvViewItemDetailsGeneral.Visible = false;
        btnGeneralPurchaseOreder1.Visible = true;


    }
    #endregion



    #region CreatePurchaseOrder

    /// <summary>
    /// Create Purchase Order from Purchase Request
    /// </summary>
    protected void CreateProductionWisePurchaseOrder()
    {
        int vendorId = 0;

        if (grvMaterialDetails.Rows.Count > 0)
        {
            int meterialCount = 0;
            int requestId = grdSelectUniqId;
            int materialId = 0;
            int quantity = 0;
            int purchaseOrderId = 0;
            DataSet vendorDS = purchase.GetVendorCountByRequestId(requestId);
                            purchaseOrderId = purchase.InsertPurchaseOrder(requestId,  requestType, requesterId);

            for (int count = 0; count < vendorDS.Tables[0].Rows.Count; count++)
            {
                string vendor = vendorDS.Tables[0].Rows[count]["PreferedVendor"].ToString();
                if (vendor != "" || vendor != string.Empty)
                    vendorId = Convert.ToInt16(vendor);
                string vendorCount = vendorDS.Tables[0].Rows[count]["vendorCount"].ToString();
                DataSet materialDS = purchase.GetMaterialDSByVendorID(requestId, vendorId);

                linkKey = purchaseOrderId;
                for (meterialCount = 0; meterialCount < materialDS.Tables[0].Rows.Count; meterialCount++)
                {
                    materialId = Convert.ToInt16(materialDS.Tables[0].Rows[meterialCount]["MaterialID"].ToString());
                    quantity = Convert.ToInt16(materialDS.Tables[0].Rows[meterialCount]["Quantity"].ToString());
                    bool status = purchase.InsertPurchaseOrderBOMList(purchaseOrderId, materialId, "", quantity);
                }
            }
            int requesterId1 = 0;
            if (Session["UserId"] != null)
                requesterId1 = Convert.ToInt16(Session["UserId"].ToString());
            int requestTypeId = requestCreate.FindRequestTypeId("PurchaseOrder");
            int requestListUniqId = requestCreate.CreateRequest("PurchaseOrder", 0, purchaseOrderId);
            requestListUniqRecordNumber = requestListUniqId;
            bool status1 = purchase.UpdateReQuestStatus(purchaseOrderId, requestTypeId, requesterId1);

            MessageBox.Show("Successfully created Purchase Order");
           // CreateInBox(requestId);
          //  ProductionClearControls();
        }
        else
        {
            MessageBox.Show("Please select an Item fro the above table");
        }
    }
    /// <summary>
    /// Create Purchase Order from Purchase Request
    /// </summary>
    /// <param name="sender"></param>
    /// <param name="e"></param>
    protected void btnCreatePurchaseOrder_Click(object sender, EventArgs e)
    {
        CreateProductionWisePurchaseOrder();
        btnProductionWiseSubmit.Visible = false;
        btnCreatePurchaseOrder.Visible = false;
        btnProductionSubmit.Visible = true;
        btnProductionSubmit1.Visible = true;
    }
    protected void btnGeneralSubmit_Click(object sender, EventArgs e)
    {
        bool status;
        status = purchase.UpdateStepStatus(1, 2, requestListUniqRecordNumber);
        if (status)
        {
            MessageBox.Show("Successfully Submitted ..");
            btnGeneralSubmit.Visible = false;
            btnGeneralSubmit1.Visible = false;
            btnGenaralForward.Visible = true;
            btnGenaralForward1.Visible = true;
        }
        else
            MessageBox.Show("Failed to Submit ");
    }
    
    protected void btnProductionSubmit_Click(object sender, EventArgs e)
    {
        bool status;
        status = purchase.UpdateStepStatus(1, 2, requestListUniqRecordNumber);
        if (status)
        {
            MessageBox.Show("Successfully Submitted ..");
            btnProductionSubmit.Visible = false;
            btnProductionSubmit1.Visible = false;
            btnProductionForward.Visible=true;
            btnProductionForward1.Visible=true;
        }
        else
            MessageBox.Show("Failed to Submit ");
    }
    protected void btnGenaralForward_Click(object sender, EventArgs e)
    {
        if (linkKey != 0)
        {
            int requestTypeId = requestCreate.FindRequestTypeId("PurchaseOrder");
            Session["UserManager_Control"] = "Purchase/ucManuallySendForApproval.ascx";
            Response.Redirect("BusinessProcessAutomation.aspx?linkKey=" + System.Convert.ToInt32(linkKey) + "&RequestType=" + requestTypeId + "&RequestLinkId=" + requestListUniqRecordNumber);
            grdselectGeneralUniqId = 0;
        }
        else
        {
            MessageBox.Show("Failed to Forward the Purchase Request");
        }
    }
    protected void btnProductionForward_Click(object sender, EventArgs e)
    {
        if (linkKey != 0)
        {
            int requestTypeId = requestCreate.FindRequestTypeId("PurchaseOrder");
            Session["UserManager_Control"] = "Purchase/ucManuallySendForApproval.ascx";
            Response.Redirect("BusinessProcessAutomation.aspx?linkKey=" + System.Convert.ToInt32(linkKey) + "&RequestType=" + requestTypeId + "&RequestLinkId=" + requestListUniqRecordNumber);

        }
        else
        {
            MessageBox.Show("Failed to Forward the Purchase Request");
        }
    }
    /// <summary>
    /// 
    /// </summary>
    /// <param name="sender"></param>
    /// <param name="e"></param>
    protected void btnNewProduction_Click(object sender, EventArgs e)
    {
        ProductionClearControls();
    }
    /// <summary>
    /// Clear the controls
    /// </summary>
    protected void ProductionClearControls()
    {
        grdSelectUniqId = 0;
        linkKey = 0;
        ddlProductName.SelectedIndex = 0;
        txtQty.Text = string.Empty;
        grvMaterialDetails.DataSource = null;
        grvMaterialDetails.DataBind();
        txtRemarks.Text = string.Empty;
        txtActualLeadTime.Text = DateTime.Now.ToShortDateString();
        txtDueDate.Text = DateTime.Now.ToShortDateString();
        pnlView.Visible = false;
        pnlView1.Visible = false;
        btnCreatePurchaseOrder.Visible = false;
        btnProductionWiseSubmit.Visible = false;
    }

    protected void grvViewPurchasedItems_SelectedIndexChanged(object sender, EventArgs e)
    {
        pnlView.Visible = true;
        pnlView1.Visible = true;
        btnCreatePurchaseOrder.Visible = true;
        btnProductionWiseSubmit.Visible = true;
        GridViewRow row = grvViewPurchasedItems.SelectedRow;
        string lbluniqId = ((Label)row.FindControl("lblUniqID")).Text;
        int purchaseRequestID = Convert.ToInt16(lbluniqId);
        grdSelectUniqId = purchaseRequestID;
        linkKey = grdSelectUniqId;
        ddlProductName.SelectedValue = ((Label)row.FindControl("lblProductID")).Text;
        txtQty.Text = ((Label)row.FindControl("lblQty")).Text;
        txtDueDate.Text = ((Label)row.FindControl("lblDate")).Text;
        txtActualLeadTime.Text = ((Label)row.FindControl("lblActualDate")).Text;

        requesterId = Convert.ToInt16(((Label)row.FindControl("lblRequesterId")).Text);
        if (purchaseRequestID != 0)
        {
            int productId = Convert.ToInt16(ddlProductName.SelectedValue);
            DataSet purchaseDS = purchase.GetPrchasedItemsByRequestId(purchaseRequestID);
            grvMaterialDetails.DataSource = purchaseDS;
            grvMaterialDetails.DataBind();
        }
    }

    protected void btnGeneralNew_Click(object sender, EventArgs e)
    {
        Button4.Visible = false;
        btnGeneralPurchaseOreder1.Visible = false;
        grvViewItemDetailsGeneral.DataSource = null;
        grvViewItemDetailsGeneral.DataBind();
        pnlGeneralView.Visible = false;
        btnGeneralPurchaseOreder.Visible = false;
        Session["hasrequestLinkId"] = null ;
        Session["requestTypeId"] = null;
        grdselectGeneralUniqId = 0;
    }

  
    protected void btnGeneralPurchaseOreder_Click(object sender, EventArgs e)
    {
        if (grvViewItemDetailsGeneral.Rows.Count > 0)
        {
            int purchaseOrderId = 0;
            int requestId = grdselectGeneralUniqId;
            purchaseOrderId = purchase.InsertPurchaseOrder(requestId, requestType, requesterId);
            linkKey = purchaseOrderId;
            foreach (GridViewRow gvr in grvViewItemDetailsGeneral.Rows)
             {
                 string  materialName = ((TextBox)gvr.Cells[1].FindControl("txtProduct1")).Text;
                 string qty=((TextBox)gvr.Cells[1].FindControl("txtRequiredQty1")).Text;
                 int quantity = Convert.ToInt16(qty);
                 bool status = purchase.InsertPurchaseOrderGeneral(purchaseOrderId, 0, materialName, quantity);

             }
            

            int requesterId1 = 0;
            if (Session["UserId"] != null)
                requesterId1 = Convert.ToInt16(Session["UserId"].ToString());
            int requestTypeId = requestCreate.FindRequestTypeId("PurchaseOrder");
            int requestListUniqId = requestCreate.CreateRequest("PurchaseOrder", 0, purchaseOrderId);
            requestListUniqRecordNumber = requestListUniqId;
            bool status1 = purchase.UpdateReQuestStatus(purchaseOrderId, requestTypeId, requesterId1);

            btnGeneralPurchaseOreder.Visible = false;
            btnGeneralPurchaseOreder1.Visible = false;
            btnGeneralSubmit1.Visible = true;
            btnGeneralSubmit.Visible = true;


           // CreateInBox(requestId);
            MessageBox.Show("Sucessfully Created");
        }
        else
        {
            MessageBox.Show("Please select an item from the above table");
        }
    }

    protected void btnEditGeneralPurchase_Click(object sender, EventArgs e)
    {
        pnlGeneralView.Visible = true;
        btnGeneralPurchaseOreder.Visible = true;
        
        grvViewItemDetailsGeneral.Visible = true;
        string path = string.Empty;
        ImageButton btn = (ImageButton)sender;
        string[] CommandArgument = btn.CommandArgument.Split(',');
        string requestNo = CommandArgument[0];
        string statusNo = CommandArgument[1];
        int requestId = Convert.ToInt16(requestNo);
        statusId = Convert.ToInt16(statusNo);
        grdselectGeneralUniqId = requestId;
        DataSet purchasedItemDS = purchase.GetGeneralPurchasedDetailsByRequestId(requestId);
        grvViewItemDetailsGeneral.DataSource = purchasedItemDS;
        grvViewItemDetailsGeneral.DataBind();
    }

    protected void CreateInBox(int requestId)
    {
        int requestTypeId = requestCreate.FindRequestTypeId("PurchaseOrder");
        //hideee
      //  requestCreate.CreateRequest("PurchaseOrder", 0, requestId);
        bool status = purchase.UpdateReQuestStatus(requestId, requestTypeId, 10);
        int inboxUniqId = inBoxCreate.CreateInBox(requestTypeId, 10, requestId);
        bool status1 = inBoxCreate.UpdateInBoxStatus(inboxUniqId, 10, 1, txtGeneralPurchaseRemarks.Text);

    }
    #endregion

}
